/**
 * Created by zqk on 2018/5/20.
 */
$(document).ready(function () {

    var form = new xhForm($('#xh_form'));
    var iWorkOrderId = addressUri.getParam('iWorkOrderId');
    var ifNew = addressUri.getParam('ifNew');
    var iParentId = addressUri.getParam('iParentId');
    var url;
    var userIds = [];
    var templateIds = [];
    form.parse();
    $(".tFromAt").datetimepicker({
        format: 'yyyy-mm-dd  hh:00:00',
        forceParse: 0,
        startDate: '2010-01-01',
        minView: 1,
        language: 'zh-CN',
        autoclose: true
    }).on('changeDate', function (ev) {
        var startdate = new Date(ev.date);
        var start = Date.parse(startdate) / 1000;
        var end = $('.tEndAt').val();
        if (end) {
            var enddate = new Date(end);
            var endtime = Date.parse(enddate) / 1000;
            if (endtime <= start) {
                window.top.xhTop.showError('错误', '开始时间不能大于完成时间');
            }
        }
    });
    $(".tEndAt").datetimepicker({
        format: 'yyyy-mm-dd  hh:00:00',
        forceParse: 0,
        startDate: '2010-01-01',
        minView: 1,
        language: 'zh-CN',
        autoclose: true
    }).on('changeDate', function (ev) {
        var enddate = new Date(ev.date);
        var end = Date.parse(enddate) / 1000;
        var start = $('.tFromAt').val();
        if (start) {
            var startdate = new Date(start);
            var starttime = Date.parse(startdate) / 1000;
            if (end <= starttime) {
                window.top.xhTop.showError('错误', '开始时间不能大于完成时间');
            }
        }
    });


    //滚动进度条 start
    var tag = false, ox = 0, left = 0, bgleft = 0;
    $('.w-progress_btn').mousedown(function (e) {
        ox = e.pageX - left;
        tag = true;
    });
    $(document).mouseup(function () {
        tag = false;
    });
    $('.w-progress').mousemove(function (e) {//鼠标移动
        if (tag) {
            left = e.pageX - ox;
            if (left <= 0) {
                left = 0;
            } else if (left > 120) {
                left = 120;
            }
            $('.w-progress_btn').css('left', left);
            $('.w-progress_bar').width(left);
            $('.text').html(parseInt((left / 120) * 100) + '%');
            $('#iProcess').val(parseInt((left / 120) * 100));
        }
    });
    $('.w-progress_bg').click(function (e) {//鼠标点击
        if (!tag) {
            bgleft = $('.w-progress_bg').offset().left;
            left = e.pageX - bgleft;
            if (left <= 0) {
                left = 0;
            } else if (left > 120) {
                left = 120;
            }
            $('.w-progress_btn').css('left', left);
            $('.w-progress_bar').animate({width: left}, 120);
            $('.text').html(parseInt((left / 120) * 100) + '%');
            $('#iProcess').val(parseInt((left / 120) * 100));
        }
    });

    //滚动进度条 end

    //获取and创建工单执行人列表
    $.ajax({
        url: moduleUrl + 'workorder/getUserIds',
        type: 'POST',
        dataType: 'json',
        async: false,//同步才能赋值
        success: function (data) {
            userIds = data;
        },
        error: function (data) {
            console.log(data);
        }
    });
    var appPackDom = $('#executorIds');
    if (userIds.length > 0) {
        var appArr = [];

        $.each(userIds, function (id, value) {
            appArr.push({id: value['iUserId'], text: value['sStaffName']});
        });
        appPackDom.select2({
            placeholder: '选择执行人',
            data: appArr
        });
    }
    //获取工单执行人列表end

    //获取and创建工单模板列表

    $.ajax({
        url: moduleUrl + 'workorder/getTemplateIds',
        type: 'POST',
        dataType: 'json',
        async: false,//同步才能赋值
        success: function (data) {
            templateIds = data;
        },
        error: function (data) {
            console.log(data);
        }
    });
    var templateDom = $('#templateId');
    if (templateIds.length > 0) {
        var templateArr = [{id: '', text: ''}];
        $.each(templateIds, function (id, value) {
            templateArr.push({id: value['iId'], text: value['sName']});
        });
        templateDom.select2({
            placeholder: '选择模板',
            data: templateArr
        }).change(function (e) {
            $('#sWorkOrderName').val(templateDom.find("option:selected").text());
        });
    } else {
        $('.template').hide();
    }
    if (ifNew != 1 || iParentId != undefined) {
        templateDom.prop("disabled", true);
    }

    //获取工单模板列表end

    var path = [];
    var con = [];
    // 新建or编辑工单
    if (iWorkOrderId != null) { //edit
        $.ajax({
            url: moduleUrl + 'workorder/getWorkOrderInfo',
            data: {
                iWorkOrderId: iWorkOrderId,
            },
            type: 'POST',
            dataType: 'json',
            async:false,
            success: function (data) {
                path = data.sEnclosure;
                $.each(path, function (index, value) {
                    $('#iParentId').before('<input name="enclosureUrl[]" type="hidden" value="' + value + '">');
                    var num = value.lastIndexOf('.');
                    var nameNum = value.lastIndexOf('/');
                    var name = value.slice(nameNum+1)
                    var str = value.slice(num + 1).toLowerCase();
                    var text = ['txt'];
                    var image = ['jpg','jpeg','png','gif','bpm'];
                    var office = ['doc','xls','ppt','xlsx','docx'];
                    var pdf = ['pdf'];
                    if (text.indexOf(str)!=-1){
                        con.push({type: "text", caption: name,  url: moduleUrl + "workorder/delFile", key: index+1});
                    }
                    if (image.indexOf(str)!=-1){
                        con.push({type: "image",caption: name,  url: moduleUrl + "workorder/delFile", key: index+1});
                    }
                    if (office.indexOf(str)!=-1){
                        con.push({type: "other",caption: name,  url: moduleUrl + "workorder/delFile", key: index+1});
                    }
                    if (pdf.indexOf(str)!=-1){
                        con.push({type: "pdf", caption: name, url: moduleUrl + "workorder/delFile", key: index+1});
                    }
                });
                form.fill(data);
                $('#iParentId').val(data.iParentId);
                $('#executorIds').removeAttr('multiple');
                $("#executorIds").val(data.executorIds);
                $("#executorIds").select2();

                $("#templateId").val(data.iTemplateId);
                $("#templateId").select2();

                var left = (data.iProcess / 100) * 120;
                $('.w-progress_btn').css('left', left);
                $('.w-progress_bar').width(left);
                $('.text').html(parseInt((left / 120) * 100) + '%');
                $('#iProcess').val(parseInt((left / 120) * 100));
            },
            error: function (data) {
                console.log(data);
            }
        });
    } else { //create
        if (iParentId != null) {
            $('#iParentId').val(iParentId);
            $('#executorIds').removeAttr('multiple');
            $("#executorIds").select2();
        }
        form.bindRequired($('#bt_modal_confirm', parent.document));
    }
    //工单附件
    //工单预计开始时间与工单预计结束时间 校验
    $("#fileInput").fileinput('destroy').fileinput({
        language: 'zh', //设置语言
        uploadUrl: moduleUrl + 'workorder/uploadFile', //上传的地址
        allowedFileExtensions: ['jpg', 'jpeg', 'png', 'gif', 'bpm', 'xlsx', 'docx', 'doc', 'pdf', 'xls', 'txt','rar','zip',],//接收的文件后缀
        //编辑已成功上传过的图片
        overwriteInitial: false,
        initialPreviewAsData: true,
        initialPreviewFileType: 'image',
        initialPreview: path, //要显示的图片的路径
        initialPreviewConfig:con,
        initialPreviewShowDelete: true,
        //
        allowedPreviewTypes: ['image'],
        uploadAsync: true, //默认异步上传
        showUpload: true, //是否显示上传按钮
        showCaption: false,//是否显示标题
        dropZoneEnabled: false,
        browseClass: "btn btn-primary", //按钮样式
        maxFileSize: 50000,
        maxFileCount: 10, //表示允许同时上传的最大文件个数
        enctype: 'multipart/form-data',
        validateInitialCount: true,
        height: 200,
        previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
        msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！"
    });

    $("#fileInput").on("fileuploaded", function (event, data, previewId, index) {
        var url = data.response.msg.url;
        $('#iParentId').before('<input name="enclosureUrl[]" type="hidden" value="' + url + '">');
    });

    $("#fileInput").on("filesuccessremove", function (event, id) {
        var num = id.lastIndexOf('-');
        var str = id.slice(num + 1);
        $('input[name="enclosureUrl[]"]').eq(str).remove();
    });
    $("#fileInput").on("filedeleted", function (event, key, jqXHR, data) {
        $('input[name="enclosureUrl[]"]').eq(key-1).remove();
    });


    //提交
    $('#bt_modal_confirm', parent.document).click(function () {
        xhExtra.setBtnLoading($('#bt_modal_confirm', parent.document));
        $('#bt_modal_confirm', parent.document).addClass('disabled');
        var start = $('.tFromAt').val();
        var startdate = new Date(start);
        var starttime = Date.parse(startdate) / 1000;
        var end = $('.tEndAt').val();
        var enddate = new Date(end);
        var endtime = Date.parse(enddate) / 1000;

        if (starttime && endtime && (endtime <= starttime)) {
            $('.tFromAt').focus();
            return false;
        }
        if (ifNew == 1) {
            url = moduleUrl + 'workorder/newWorkOrder';
        } else {
            url = moduleUrl + 'workorder/editWorkOrder';
        }
        $.ajax({
            url: url,
            data: $('#xh_form').serialize(),

            type: 'POST',
            success: function (data) {
                window.top.xhTop.showSuccess(
                    data.msg
                );
                window.top.xhTop.closeModal();
                window.top.xhTop.getActiveFrame().workOrderList.treegrid('reload');
            },
            error: function (data) {
                xhExtra.setBtnNormal($('#bt_modal_confirm', parent.document));
                $('#bt_modal_confirm', parent.document).removeClass('disabled');
                window.top.xhTop.showError(
                    data.responseJSON.error,
                    data.responseJSON.msg
                );
            }
        });
    });
    // modalBind.bindClick();

});